package com.example.firstapp.core;

import java.util.List;

import android.location.Location;

import com.example.firstapp.entity.Restaurant;

public class SpatialContext implements UserContext {

	private List<Restaurant> restaurants;
	private Location location;
	private int minDist = 1000000, maxDist = 0;

	public SpatialContext(List<Restaurant> restaurants, Location loc) {
		this.restaurants = restaurants;
		this.location = loc;
		for (Restaurant res : restaurants) {
			int distance = distanceTo(res);
			if (minDist > distance) {
				minDist = distance;
			}
			if (maxDist < distance) {
				maxDist = distance;
			}
		}
	}

	@Override
	public double evaluate(Restaurant restaurant) {
		int distance = distanceTo(restaurant);
		if (maxDist == minDist)
			return 10.0;
		return 10.0 * (maxDist - distance) / (maxDist - minDist);
	}

	public int distanceTo(Restaurant restaurant) {
		String urlString = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
				+ location.getLatitude()
				+ ","
				+ location.getLongitude()
				+ "&destinations="
				+ restaurant.getLatitude()
				+ ","
				+ restaurant.getLongitude()
				+ "&mode=walking&sensor=false&units=metric";
		try {
			CalculateDistanceThread t = new CalculateDistanceThread(urlString);
			t.start();
			t.join();

			return t.getDist();
		} catch (Exception e) {
			return 100000;
		}
	}
}
